/**
 * 四大金刚选择器
 */

import PickerView from '../PickerView';
import { Button, Popup, Tabs, Tag } from '@nutui/nutui-react-taro';
import { View, ScrollView } from '@tarojs/components';
import type { FC, CSSProperties } from 'react';
import { useState, useEffect, useMemo } from 'react';
import { Empty } from '@/components';
import { getApiBigGet } from '@/api';
import type { GetApiBigGetResponse } from '@/api';
import { Checklist } from '@nutui/icons-react-taro';
import './index.scss';
import classnames from 'classnames';
import { useRequest } from '@/hooks';
import { isLogin } from '@/utils';

export type FourGreatDataProps = GetApiBigGetResponse['0'];

type FourGreatInnerDataProps = Omit<FourGreatDataProps, 'id'> & {
  id: string;
};

const PREFIX_CLS = 'm-four-great-picker';

interface FourGreatPickerProps {
  className?: string;
  style?: CSSProperties;
  placeholder?: string;
  value?: FourGreatDataProps[];
  onChange?: (value: FourGreatDataProps[]) => void;
}

const Fields = [
  {
    title: '化妆师',
    value: 10,
  },
  {
    title: '司仪',
    value: 20,
  },
  {
    title: '摄影',
    value: 30,
  },
  {
    title: '婚庆',
    value: 40,
  },
];

const FourGreatPicker: FC<FourGreatPickerProps> = ({
  className,
  style,
  placeholder,
  value = [],
  onChange,
}) => {
  const [visible, setVisible] = useState(false);
  const [current, setCurrent] = useState<FourGreatInnerDataProps[]>([]);

  const [active, setActive] = useState<number>(10);

  useEffect(() => {
    if (value && !!value.length) {
      setCurrent(handleFormatData.in(value));
    }
  }, [value]);

  useEffect(() => {
    if (visible && isLogin()) {
      run({
        type: active,
      });
    }
  }, [visible, isLogin()]);

  const { data, run } = useRequest(getApiBigGet, {
    defaultParams: {
      // 10:化妆师20司仪30摄影40婚庆
      type: 10,
    },
    manual: true,
    formatResult: ({ data }) => {
      // 重组一下id = bigType + id
      return data.map((item) => ({
        ...item,
        id: item.bigType + '_' + item.id,
      }));
    },
  });

  // 数据处理
  const handleFormatData = {
    in: (data: FourGreatDataProps[]) => {
      return data.map((item) => ({
        ...item,
        id: item.bigType + '_' + item.id,
      }));
    },
    out: (data: FourGreatInnerDataProps[]) => {
      return data.map((item) => ({
        ...item,
        id: +item?.id?.split('_')?.[1],
      }));
    },
  };

  const idList = useMemo(() => {
    return current.map((item) => item.id);
  }, [current]);

  return (
    <PickerView
      className={className}
      style={style}
      defaultText={placeholder}
      onClick={() => {
        setVisible(true);
      }}
    >
      <Popup
        closeable
        title="人员安排"
        position="bottom"
        visible={visible}
        onClose={() => setVisible(false)}
        className={PREFIX_CLS}
      >
        <Tabs
          direction="vertical"
          value={active}
          onChange={(v: number) => {
            setActive(v);
            if (isLogin()) {
              run({ type: v });
            }
          }}
          duration={0}
        >
          {Fields.map((item, i) => (
            <Tabs.TabPane {...item} key={i + ''}>
              {data?.length > 0 ? (
                <ScrollView className="list">
                  {data.map((d) => (
                    <View
                      className="item-wrap"
                      key={d.id}
                      onClick={(e) => {
                        e.stopPropagation();
                        // 判断是否已选择
                        if (idList.includes(d.id)) {
                          setCurrent(current.filter((id) => id !== d.id));
                        } else {
                          setCurrent([...current, d]);
                        }
                      }}
                    >
                      <View
                        className={classnames('item', {
                          active: idList.includes(d.id),
                        })}
                      >
                        <View className="name">{d.name}</View>
                        <Tag
                          className="tag"
                          plain
                          color="#4a4a4a"
                          background="#e0e0e0"
                        >
                          ¥{d.price}
                        </Tag>
                      </View>
                      {idList.includes(d.id) ? <Checklist /> : null}
                    </View>
                  ))}
                </ScrollView>
              ) : (
                <Empty title="暂无数据" />
              )}
            </Tabs.TabPane>
          ))}
        </Tabs>
        <View className="footer">
          <Button size="large" onClick={() => setVisible(false)}>
            取消
          </Button>
          <Button
            size="large"
            type="primary"
            onClick={() => {
              setVisible(false);
              onChange?.(handleFormatData.out(current));
            }}
          >
            确定
          </Button>
        </View>
      </Popup>
    </PickerView>
  );
};

export default FourGreatPicker;
